package com.ppt.android.base.mvvm.vm

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch

/**
 * 全局的 viewModel
 * @author ZouJiaCai
 * @since 2023/7/21 17:34
 */
class EventViewModel : ViewModel(){

    //与viewModel生命周期关联的协程
    private val coroutineScope : CoroutineScope
        get() = viewModelScope

    /**
     * H5唤醒App的跳转的Flow
     */
    private val h5WakeUpMutableSharedFlow: MutableSharedFlow<Any> =
        MutableSharedFlow(replay = 1)       //<--------注意这里


    /**
     * 设置H5唤醒携带的值
     */
    fun setH5WakeUpValue(bean: Any?) {
        bean?.apply {
            h5WakeUpMutableSharedFlow.tryEmit(bean)
        }
    }

    /**
     * 开始订阅,获取H5唤醒携带的值
     */
    fun getH5WakeUpValue(method: (bean: Any) -> Unit) {
        coroutineScope.launch(Dispatchers.IO) {
            h5WakeUpMutableSharedFlow.collect {
                method.invoke(it)
            }
        }
    }
}
